package service;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.security.Key;

/**
 * @author: hett
 * @date: 2022/3/14 11:34
 */
public class NIOService {

    private static int port =3210;


    public static void main(String[] args){

      try {
          ServerSocketChannel channel = ServerSocketChannel.open();
          channel.socket().bind(new InetSocketAddress(port));
          channel.configureBlocking(false);
          Selector selector = Selector.open();
          channel.register(selector, SelectionKey.OP_ACCEPT);
          ByteBuffer writeBuffer = ByteBuffer.allocate(128);
          writeBuffer.put("1101".getBytes());
          writeBuffer.flip();
          while (selector.select()>0){
              for (SelectionKey sk : selector.selectedKeys()){
                  selector.selectedKeys().remove(sk);
                  if (sk.isAcceptable()){
                      ServerSocketChannel ssc = (ServerSocketChannel) sk.channel();
                      SocketChannel sc = ssc.accept();
                      sc.configureBlocking(false);
                      sc.register(selector,SelectionKey.OP_READ);
                  }
                  if (sk.isReadable()){
                      SocketChannel sc = (SocketChannel) sk.channel();
                      ByteBuffer buff = ByteBuffer.allocate(10);
                      int readBytes =sc.read(buff);
                      if (readBytes>0){
                          buff.flip();
                          byte[] revContent = new byte[buff.remaining()];
                          buff.get(revContent);
                          System.out.println(new String(revContent));
                          sk.interestOps(SelectionKey.OP_WRITE);
                      }
                  }
                  if (sk.isWritable()){
                      writeBuffer.rewind();
                      SocketChannel sc = (SocketChannel) sk.channel();
                      sc.write(writeBuffer);
                      sk.interestOps(SelectionKey.OP_READ);
                  }
              }
          }
      } catch (IOException e) {
          e.printStackTrace();
      }
    }
}
